package me.denger.database2Word;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import me.denger.database2Word.bean.Table;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class FileUtil {
    /**
     * 模板名称
     */
    private static final String TEMPLATE_XML = "template.xml";

    /**
     * 将数据写到word文件中
     *
     * @param filePath 文件路径，覆盖写入
     * @param allTable 表列表
     * @return 表数量
     * @throws IOException
     */
    public static int write2Word(String filePath, List<Table> allTable) throws Exception {
        InputStream resourceAsStream = FileUtil.class.getClassLoader().getResourceAsStream(TEMPLATE_XML);

        Configuration configuration;
        configuration = new Configuration(Configuration.VERSION_2_3_27);
        configuration.setDefaultEncoding("UTF-8");
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        try (BufferedWriter bufferedWriter = new BufferedWriter(
                new OutputStreamWriter(
                        new FileOutputStream(filePath), configuration.getDefaultEncoding()))) {
            //处理文件体
            Template temp = new Template("", new InputStreamReader(resourceAsStream, configuration.getDefaultEncoding()), configuration);
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("allTable", allTable);
            temp.process(dataMap, bufferedWriter);
            bufferedWriter.flush();
        }

        return allTable.size();
    }

    /**
     * 将数据写到Excel文件中
     *
     * @param filePath 文件路径，覆盖写入
     * @param allTable 表列表
     * @return 表数量
     * @throws IOException
     */
    public static int write2Excel(String filePath, List<Table> allTable) throws Exception {
        // todo 将数据写到Excel文件中
        return -1;
    }
}
